package org.zhouhe.common;

import java.io.File;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;

/**
 * 本Servlet随启动而执行
 */
public class InitSystem extends HttpServlet {
	public static Logger logger = Logger.getLogger(InitSystem.class);
	private static final long serialVersionUID = 1L;
	public static Configuration freemarkerConfig = new Configuration();
	public static String webRootDir;
	public static String contextPath;
	static {
		String classRootPath = InitSystem.class.getClassLoader().getResource("/").getPath();
		webRootDir = new File(classRootPath).getParentFile().getParent();
		logger.info("webRootDir="+ webRootDir);
	}
	public InitSystem() {
		super();
	}

	public void init(ServletConfig servletConfig) throws ServletException {
		contextPath = servletConfig.getServletContext().getContextPath();
		servletConfig.getServletContext().setAttribute("ctxPath", contextPath);
		this.initFreemarkerConfiguration(servletConfig);
	};

	private void initFreemarkerConfiguration(ServletConfig servletConfig){
		try {
			freemarkerConfig.setDirectoryForTemplateLoading(new File(webRootDir));
			freemarkerConfig.setObjectWrapper(new DefaultObjectWrapper());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
